package com.example.springboot2.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot2.base.web.BaseController;
import com.example.springboot2.oa.entity.TPower;
import com.example.springboot2.oa.entity.TUser;
import com.example.springboot2.oa.service.ITPowerService;
import com.example.springboot2.tools.MakeResponse;
import com.example.springboot2.tools.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

@CrossOrigin
@RestController
@RequestMapping("/oa/t-power")
public class TPowerController extends BaseController {
    @Autowired
    private ITPowerService powerService;

    @PostMapping("setPower")
    public ResponseMessage setPower(String roleId,
                                    String menuId, int status,
                                    HttpServletRequest request) {
        ResponseMessage rsp = authentication(request);
        if (rsp != null) {
            return rsp;
        }

        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("token", request.getHeader("token"));
        TUser user = userService.getOne(wrapper);
        if (user != null && user.getRoleId() == roleId) {
            return MakeResponse.success("500", "非法设置权限");
        }

        String[] menuIdList = menuId.split(",");
        for (int i = 0; i < menuIdList.length; i++) {
            String id = menuIdList[i];
            TPower power = new TPower();
            power.setStatus(status);
            power.setRoleId(roleId);
            power.setMenuId(Integer.parseInt(id));
            QueryWrapper<TPower> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("role_id", power.getRoleId())
                    .eq("menu_id", power.getMenuId());

            if (!powerService.update(power, wrapper2)) {
                powerService.save(power);
            }
        }

        return MakeResponse.success("200", "设置权限成功");
    }
}
